package com.example.wlzz.controller.admin;
import com.example.wlzz.api.ConfigAPI;
import com.example.wlzz.constant.CookiesConstant;
import com.example.wlzz.constant.RedisConstant;
import com.example.wlzz.dto.FileLocalDTO;
import com.example.wlzz.dto.TaskDTO;
import com.example.wlzz.dto.admin.UserDTO;
import com.example.wlzz.entity.Banner;
import com.example.wlzz.entity.UserInfo;
import com.example.wlzz.entity.mongoEntity.Task;
import com.example.wlzz.entity.mongoEntity.TaskReceive;
import com.example.wlzz.enums.Del_flagEnum;
import com.example.wlzz.enums.ResultEnum;
import com.example.wlzz.repository.BannerRepository;
import com.example.wlzz.repository.UserInfoRepository;
import com.example.wlzz.repository.mapper.admin.RoleMapper;
import javax.servlet.http.Cookie;
import com.example.wlzz.repository.mapper.admin.SmsMapper;
import com.example.wlzz.repository.mapper.admin.UserMapper;
import com.example.wlzz.repository.mongoRepository.TaskReceiveRepository;
import com.example.wlzz.repository.mongoRepository.TaskRepository;
import com.example.wlzz.service.AdminService;
import com.example.wlzz.service.TaskService;
import com.example.wlzz.utils.CookieUtil;
import com.example.wlzz.utils.FileSaveLocalUtil;
import com.example.wlzz.utils.KeyUtil;
import com.example.wlzz.utils.ResultVOUtil;
import com.example.wlzz.vo.PageVO;
import com.example.wlzz.vo.ResultVO;
import com.example.wlzz.vo.TaskVO;
import com.mongodb.client.MongoCollection;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/backstage")
@Slf4j
@ApiIgnore
public class AdminController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private TaskService taskService;
    @Autowired
    private BannerRepository bannerRepository;
    @Autowired
    private AdminService adminService;
    @Autowired
    private ConfigAPI configAPI;
    @Autowired
    private TaskRepository taskRepository;
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private TaskReceiveRepository taskReceiveRepository;

    @PostMapping("/pageForUserInfo")
    public ResultVO  pageForUserInfo(@RequestParam("page") int page,
                                     @RequestParam(value = "size",defaultValue = "10") int size,
                                     Map<String,Object> map ){
            int start = (page-1)*size;  //开始
            System.out.println(start+":::"+size);
            List<UserDTO> userDTOList =  userMapper.getUserInfo(start,size);
            MongoCollection<Document> taskColleections =  mongoTemplate.getCollection("task");
            for (UserDTO userDTO : userDTOList) {
                Document document = new Document("userid",userDTO.getUser_id());
                userDTO.setTask_number(taskColleections.count(document));
            }
            return ResultVOUtil.success(userDTOList);
    }

    @PostMapping("/taskForUser")
    public ResultVO  taskForUser(@RequestParam("page") int page,
                                 @RequestParam(value = "size",defaultValue = "10") int size,
                                 @RequestParam("status") int status,
                                 @RequestParam("user_id") int user_id,
                                     Map<String,Object> map ){
        PageRequest request = PageRequest.of(page-1,size);
        PageVO pageVO = taskService.getAllSelfTask(user_id,status,request);
        return ResultVOUtil.success(pageVO);
    }
    @PostMapping("/allUser_task")
    public ResultVO  allUser_task(@RequestParam("page") int page,
                                 @RequestParam(value = "size",defaultValue = "10") int size,
                                 @RequestParam("status") int status,
                                 Map<String,Object> map ){
        PageRequest request = PageRequest.of(page-1,size);
        return ResultVOUtil.success(adminService.findAll_task(request,status));
    }
    @PostMapping("/search_user")
    public ResultVO  search_user(@RequestParam("input_user_info") String input_user_info,
                                 Map<String,Object> map){
        List<UserDTO> userDTOList = userMapper.searchUser("%"+input_user_info.trim()+"%");
        MongoCollection<Document> taskColleections =  mongoTemplate.getCollection("task");
        for (UserDTO userDTO : userDTOList) {
            Document document = new Document("userid",userDTO.getUser_id());
            userDTO.setTask_number(taskColleections.count(document));
        }
        return ResultVOUtil.success(userDTOList);
    }

    @PostMapping("/search_task")
    public ResultVO  search_task(@RequestParam("input_task") String input_task,
                                 Map<String,Object> map){
        Task task = taskRepository.findBy_id(input_task.trim());
        if(task==null){
            return ResultVOUtil.error(ResultEnum.TASK_NO_EXIST.getCode(),ResultEnum.TASK_NO_EXIST.getMessage());
        }
        com.example.wlzz.dto.admin.TaskDTO taskDTO = new com.example.wlzz.dto.admin.TaskDTO();
        BeanUtils.copyProperties(task,taskDTO);
        Long getTime = task.getCreateTime().getTime();
        taskDTO.setCreateTime(getTime.toString());
        MongoCollection<Document> loveTaskCollection =  mongoTemplate.getCollection("loveTask");
        MongoCollection<Document> commentCollention =  mongoTemplate.getCollection("comment");
        TaskVO taskVO = new TaskVO();
        UserInfo userInfo = userInfoRepository.findByUserId(taskDTO.getUserid());
        taskVO.setNickName(userInfo.getNickName());
        taskVO.setImgUrl(userInfo.getImgUrl());
        taskVO.setTask(taskDTO);
        Document document1 = new Document();
        document1.put("taskId",taskDTO.get_id());
        Document document2 = new Document();  //comment的条件
        document2.put("taskId",taskDTO.get_id());
        document2.put("delFlag",Del_flagEnum.EXIST.getCode());
        Long count =  loveTaskCollection.count(document1);
        taskVO.setLove(count.intValue());
        taskVO.setUserid(taskDTO.getUserid());
        Long commentCount =  commentCollention.count(document2);
        taskVO.setCommentCount(commentCount.intValue());
        //增加接单者
        if(taskDTO.getStatus()!=0){  //表示已被接单
            TaskReceive receive =  taskReceiveRepository.findByTaskIdAndStatus(taskVO.getTask().get_id(),taskDTO.getStatus());
            UserInfo re_userInfo = userInfoRepository.findByUserId(receive.getUserid());
            taskVO.setRe_imgUrl(re_userInfo.getImgUrl());
            taskVO.setRe_nickName(re_userInfo.getNickName());
            taskVO.setRe_userid(re_userInfo.getUserId());
        }
        return ResultVOUtil.success(taskVO);
    }
      @PostMapping("/deleteBanner")
    public ResultVO deleteBanner(@RequestParam("id") int id){
        Banner banner = bannerRepository.findById(id);
        if(banner.getFlag()==Del_flagEnum.EXIST.getCode()){
            banner.setFlag(Del_flagEnum.DELETE.getCode());
            bannerRepository.save(banner);
            return ResultVOUtil.success();
        }else{
            return ResultVOUtil.error(ResultEnum.DELETE_FAIL.getCode(),ResultEnum.DELETE_FAIL.getMessage());
        }
    }

    @PostMapping("/deleteTask")
    public ResultVO deleteTask(@RequestParam("id") String id){
        Task task = taskRepository.findBy_idAndDelFlag(id,Del_flagEnum.EXIST.getCode());
        if(task==null){
            return ResultVOUtil.error(ResultEnum.TASK_NO_EXIST.getCode(),ResultEnum.TASK_NO_EXIST.getMessage());
        }
        task.setDelFlag(Del_flagEnum.DELETE.getCode());
        taskRepository.save(task);  //保存删除
        return ResultVOUtil.success();
    }
    @PostMapping("/addBanner")
    public ResultVO addBanner(@RequestParam("banner_img") MultipartFile file,
                              @RequestParam("banner_url") String banner_url){
        try {
            String path = FileSaveLocalUtil.getYearAndMonth();   //得到路径
            String fileName = KeyUtil.genUniqueKey();
            FileSaveLocalUtil.savePic(file.getInputStream(),path,fileName);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("http://");
            stringBuilder.append(configAPI.getName());
            stringBuilder.append("/wlzzUser/getImg?");
            stringBuilder.append("flag=");
            String parameter = path+fileName;
            stringBuilder.append(URLEncoder.encode(parameter, "utf-8"));
            Banner banner = new Banner();
            banner.setFlag(Del_flagEnum.EXIST.getCode());
            banner.setCreateTime(new Date());
            banner.setImgUrl(stringBuilder.toString());
            banner.setUrl(banner_url);
            bannerRepository.save(banner);
            return ResultVOUtil.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.BANNER_ERROR.getCode(),ResultEnum.BANNER_ERROR.getMessage());
        }
    }

}
